#!/usr/bin/python3
# -*- coding: UTF-8 -*-
 
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import requests
import socket
import time

# 获取公网IP地址，添加重试机制
def get_public_ip(max_retries=5, retry_interval=5):
    for attempt in range(max_retries):
        try:
            # 使用公共API获取公网IP
            response = requests.get('https://api.ipify.org', timeout=10)
            if response.status_code == 200:
                return response.text
        except:
            try:
                # 备用API
                response = requests.get('https://ifconfig.me', timeout=10)
                if response.status_code == 200:
                    return response.text
            except:
                pass
        
        # 如果还没到最后一次尝试，则等待一段时间再重试
        if attempt < max_retries - 1:
            time.sleep(retry_interval)
    
    return "无法获取公网IP"

# 获取本地主机名和IP
def get_local_ip():
    hostname = socket.gethostname()
    local_ip = socket.gethostbyname(hostname)
    return hostname, local_ip

# 发送邮件，添加重试机制
def send_email(max_retries=3, retry_interval=5):
    # 第三方 SMTP 服务
    mail_host="smtp.xxx.com"  #设置服务器
    mail_user="xxx@xxx.com"    #用户名
    mail_pass="xxx"   #口令 
     
    sender = 'xxx'
    receivers = ['xxx@xxx.com']  # 接收邮件

    # 获取IP信息
    public_ip = get_public_ip()
    hostname, local_ip = get_local_ip()

    # 构建邮件正文
    email_content = f'''
服务器信息:
主机名: {hostname}
本地IP: {local_ip}
公网IP: {public_ip}
'''

    message = MIMEText(email_content, 'plain', 'utf-8')
    message['From'] = Header("xxx", 'utf-8')
    message['To'] = Header("xxx", 'utf-8')
     
    subject = '服务器重启，公网IP'
    message['Subject'] = Header(subject, 'utf-8')
     
    for attempt in range(max_retries):
        try:
            smtpObj = smtplib.SMTP() 
            smtpObj.connect(mail_host, 25)    # 25 为 SMTP 端口号
            smtpObj.login(mail_user, mail_pass)  
            smtpObj.sendmail(sender, receivers, message.as_string())
            print(f"邮件发送成功，公网IP: {public_ip}")
            return True
        except smtplib.SMTPException as e:
            print(f"尝试 {attempt+1}/{max_retries}: 无法发送邮件: {e}")
            if attempt < max_retries - 1:
                time.sleep(retry_interval)
    
    return False

# 主程序
if __name__ == "__main__":
    send_email()